<template>
  <v-page
    v-model="refreshing"
    background="#f5f6fa"
    header-background="white"
    footer-background="white"
    :empty="state === 'finished' && !orderList.length && !aftersalesList.length"
    empty-oss-src="empty-order.png"
    empty-text="暂无订单"
    padding-top="24rpx"
    @refresh="refreshHandle"
    @tolower="getOrderList"
  >
    <template #header>
      <v-navbar title="订单" native />
      <view class="tabs-container">
        <wd-tabs
          color="#ff2f3b"
          line-height="4rpx"
          line-width="50rpx"
          :model-value="tabIndex"
          @update:model-value="changeTabIndex"
        >
          <view v-for="tab in orderListTab" :key="tab.status">
            <wd-tab :title="tab.name" />
          </view>
        </wd-tabs>
        <view class="tabs-mask" />
      </view>
    </template>
    <template #default>
      <order-item
        v-for="order in orderList"
        :key="order.id"
        :order="order"
        @refresh="refreshOrderList"
        @show-comment="showCommentPopup"
        @buy-again="showBuyAgain"
      />
      <aftersales-item
        v-for="aftersales in aftersalesList"
        :key="aftersales.id"
        :aftersales="aftersales"
        @refresh="refreshOrderList"
      />
      <v-loadmore :state="state" @reload="getOrderList" />
    </template>
    <template #popup>
      <order-buy-again-select-popup
        v-if="productDetail"
        v-model:show="isShowSelect"
        type="order"
        :product="productDetail"
        :sku-info="buyAgainProduct?.sku"
      />
      <order-details-comment-apply-popup
        v-if="commentProduct"
        v-model:show="isShowCommentPopup"
        :product="commentProduct"
      />
    </template>
  </v-page>
</template>

<script setup lang="ts">
import OrderDetailsCommentApplyPopup from './modules/order-details-comment-apply-popup.vue';
import OrderBuyAgainSelectPopup from './modules/order-buy-again-select-popup.vue';
import OrderItem from './modules/order-item.vue';
import AftersalesItem from './modules/aftersales-item.vue';

const tabIndex = ref(0);
const orderListTab = [
  { name: '全部', status: 'ALL' },
  { name: '待付款', status: 'UNPAID' },
  { name: '待发货', status: 'UNSHIPPED' },
  { name: '待收货', status: 'SHIPPED' },
  { name: '已收货', status: 'RECEIVED' },
  { name: '已完成', status: 'COMPLETED' },
  { name: '待评价', status: 'TO_BE_COMMENT' },
  { name: '售后', status: 'AFTERSALES' }
] as const;

const changeTabIndex = (index: number) => {
  tabIndex.value = index;
  pageIndex.value = 1;
  orderList.value = [];
  aftersalesList.value = [];
  state.value = undefined;
  getOrderList();
};

const pageIndex = ref(1);
const state = ref<'loading' | 'finished' | 'error'>();
const orderList = ref<OrderVO[]>([]);
const aftersalesList = ref<BackRefundVO[]>([]);

const getOrderList = async () => {
  if (state.value !== undefined && state.value !== 'error') return;
  const status = orderListTab[tabIndex.value].status;
  state.value = 'loading';
  if (status === 'AFTERSALES') {
    const response = await $api.getBackRefundList({
      page_no: pageIndex.value,
      page_size: 10,
      detail: true
    });
    switch (response.__error) {
      case undefined:
        aftersalesList.value.push(...(response.data?.list ?? []));
        pageIndex.value++;
        if (aftersalesList.value.length >= response.data?.total) {
          state.value = 'finished';
        } else {
          state.value = undefined;
        }
        break;
      default:
        state.value = 'error';
    }
  } else if (status === 'TO_BE_COMMENT') {
    const response = await $api.getOrderQueryList({
      page_no: pageIndex.value,
      page_size: 10,
      status: 'RECEIVED',
      comment_status: 'TO_BE_COMMENT',
      detail: true
    });
    switch (response.__error) {
      case undefined:
        orderList.value.push(...(response.data?.list ?? []));
        pageIndex.value++;
        if (orderList.value.length >= response.data?.total) {
          state.value = 'finished';
        } else {
          state.value = undefined;
        }
        break;
      default:
        state.value = 'error';
    }
  } else {
    const response = await $api.getOrderQueryList({
      page_no: pageIndex.value,
      page_size: 10,
      status
    });
    switch (response.__error) {
      case undefined:
        orderList.value.push(...(response.data?.list ?? []));
        pageIndex.value++;
        if (orderList.value.length >= response.data?.total) {
          state.value = 'finished';
        } else {
          state.value = undefined;
        }
        break;
      default:
        state.value = 'error';
    }
  }
};

const refreshOrderList = async () => {
  pageIndex.value = 1;
  state.value = undefined;
  orderList.value = [];
  aftersalesList.value = [];
  getOrderList();
};

// 监听后，其他页面回来的时候才判断刷新
let needToRefresh = false;
const setNeedToRefresh = () => (needToRefresh = true);
onLoad((query) => {
  if (query?.status) {
    const index = orderListTab.findIndex(
      (item) => item.status === query.status
    );
    if (index !== -1) {
      tabIndex.value = index;
    }
  }
  getOrderList();
  uni.$on('refresh-order-list', setNeedToRefresh);
});
onShow(() => {
  if (needToRefresh) {
    refreshOrderList();
    needToRefresh = false;
  }
});
onUnload(() => {
  uni.$off('refresh-order-list', setNeedToRefresh);
});

const refreshing = ref(false);
const refreshHandle = async () => {
  pageIndex.value = 1;
  orderList.value = [];
  aftersalesList.value = [];
  state.value = undefined;
  refreshing.value = true;
  await getOrderList();
  refreshing.value = false;
};

const buyAgainProduct = ref<OrderDetailVO>();
const productDetail = ref<SpuVO>();
const getProductDetails = async () => {
  if (!buyAgainProduct.value) return;
  if (buyAgainProduct.value.spu_id === productDetail.value?.id) return;
  const response = await $api.getSearchIdDetail(buyAgainProduct.value.spu_id);
  switch (response.__error) {
    case undefined:
      productDetail.value = response.data;
      break;
  }
};
const isShowSelect = ref(false);
const showBuyAgain = async (product: OrderDetailVO) => {
  buyAgainProduct.value = product;
  await getProductDetails();
  isShowSelect.value = true;
};

const commentProduct = ref<OrderDetailVO>();
const isShowCommentPopup = ref(false);
const showCommentPopup = (product: OrderDetailVO) => {
  commentProduct.value = product;
  isShowCommentPopup.value = true;
};
</script>

<style lang="scss" scoped>
.tabs-container {
  position: relative;
  padding: 0 12rpx;
  box-sizing: border-box;
  .tabs-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(
      to right,
      rgba(255, 255, 255, 1),
      rgba(255, 255, 255, 0) 36rpx,
      rgba(255, 255, 255, 0) calc(100% - 36rpx),
      rgba(255, 255, 255, 1)
    );
    pointer-events: none;
  }
  :deep(scroll-view) {
    scrollbar-width: 0;
    &::-webkit-scrollbar {
      display: none;
    }
  }
}
</style>
